package com.tuoyu.peopletest.view.ac;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.KeyboardUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;

import com.stresscube.stresscubetest.ScanTest;
import com.stresscube.stresscubetest.TestCallback;
import com.stresscube.usbdevice.USBDevicePDHIDWithAddress;
import com.stresscube.usbdevice.data.ParaScan;
import com.stresscube.usbdevice.utils.WorkMessage;
import com.tuoyu.peopletest.R;
import com.tuoyu.peopletest.common.Constant;
import com.tuoyu.peopletest.entity.DataBean;
import com.tuoyu.peopletest.model.data.SaveAppData;
import com.tuoyu.peopletest.utils.SCLogUtils;
import com.tuoyu.peopletest.utils.SCTimeUtils;

import java.util.ArrayList;
import java.util.List;

public class MainNewActivity extends NomalBaseActivity implements TestCallback {
    static final String TAG = "Main";

    private static final int TEST_ITEM_CORTISOL = 0;
    private static final int TEST_ITEM_PROGESTERONE = 1;
    private static final int WAVE_LENGTH_365 = 0;
    private static final int WAVE_LENGTH_470 = 1;
    private static final int WAVE_LENGTH_525_40 = 2;
    private static final int WAVE_LENGTH_525_80 = 3;
    private static final boolean FLUORESCENCE_VALLEY = false;
    private static final boolean COLLOIDAL_GOLD_VALLEY = true;
    private static final int CODE_SCAN_RESULT = 1206;

    LineChart mLineChart;   //显示曲线
    TextView mtvMessage; //过程消息显示
    TextView mtvResult; //结果显示
    byte ledPosition = (byte) 0x03; //孔位为3
    byte mADPosition = (byte) 0x01; //AD孔位
    int mBrightness;
    boolean mbValley; //峰或谷
    ArrayList<Integer> mListResult = new ArrayList<Integer>(); //保存读出来的数据

    int mStart, mStop, mStep = 2;
    private int mArea1;
    private int mArea2;
    private int mWaveLength; //0-365 1-470 2-525.40 3-525.80
    private String waveLength;

    private EditText etNumber; //样品编号
    private RadioGroup rgTestItems; //测试项目
    private int mTestItem;
    private String mstrTestItem;
    private String mstrTestResult;
    private String mScanStr;
//    double k=0,b=0;
    double k=-0.9737,b=1.0312;
    private TextView tvScanResult;
    ScanTest mScanTest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void initContentView() {
        setContentView(R.layout.activity_main_new);
        InitData();
    }

    @Override
    public void initChildView() {

    }

    @Override
    public void initData() {
        super.initData();

    }

    @Override
    public void initListener() {
        super.initListener();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mScanTest.init();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mScanTest.release();
    }

    void InitData() {
        mScanTest=new ScanTest(this, this);
        tvScanResult = findViewById(R.id.tv_scan_result);
        findViewById(R.id.v_et_main).setVisibility(View.VISIBLE);
        findViewById(R.id.v_main02).setVisibility(View.GONE);
        etNumber = findViewById(R.id.et_input);
        rgTestItems = findViewById(R.id.rgTestItems);

        mtvMessage = findViewById(R.id.tvMessage);
        mtvResult = findViewById(R.id.tvResult);
        mLineChart = findViewById(R.id.lineChart_01);
        mListResult.clear();

        mScanStr=SaveAppData.getScanResult();
        GetTestPara();
        tvScanResult.setText(mScanStr);
    }

    public void DisplayMessage(String msg) {
        mtvMessage.setText(msg + "\r\n" + mtvMessage.getText());
        Log.d(TAG, msg);
    }
    public void DisplayResult(String msg) {
        mtvResult.setText(msg + "\r\n" + mtvResult.getText());
        Log.d(TAG, msg);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnScanRead:
                findViewById(R.id.btnScanRead).setVisibility(View.INVISIBLE);
                ScanRead();
                break;
            case R.id.tv_btn_scan:
                //扫码
                Intent scanIntent = new Intent(this, ScanActivity.class);
                startActivityForResult(scanIntent, CODE_SCAN_RESULT);
                break;
            case R.id.tv_btn_sure:

                //样本输入确定
                KeyboardUtils.hideSoftInput(this);
                findViewById(R.id.v_et_main).setVisibility(View.GONE);
                findViewById(R.id.v_main02).setVisibility(View.VISIBLE);
                GetInput();
                break;
        }
    }

    private void GetInput() {
        mstrTestItem = ((RadioButton) findViewById(rgTestItems.getCheckedRadioButtonId())).getText().toString();
        switch (rgTestItems.getCheckedRadioButtonId()) {
            case R.id.rbCortisol:
                mTestItem = TEST_ITEM_CORTISOL;
                mWaveLength = WAVE_LENGTH_365;
                mBrightness = 600;
                mbValley = FLUORESCENCE_VALLEY;
                mStart = 25;
                mStop = 160;
                waveLength = "470";
                break;
        }
    }

    private void ScanRead() {
        mListResult.clear();
        if(mScanTest.DoTest()){
            mStart=mScanTest.start;
            mStop=mScanTest.stop;
            mStep=mScanTest.step;
        }
    }

    void SendDispMessage(String str) {
        Message message = new Message();
        message.what = 1;
        message.obj = str;
        mHandler.sendMessage(message);
    }

    void SendDispData(int[] data) {
        Message message = new Message();
        message.what = 2;
        message.obj = data;
        mHandler.sendMessage(message);
    }

    void DispCurve() {
        Message message = new Message();
        message.what = 3;
        mHandler.sendMessage(message);
    }
    void SendDispData(int data) {
        Message message = new Message();
        message.what = 4;
        message.obj = data;
        mHandler.sendMessage(message);
    }

    void SendShowTestButton() {
        Message message = new Message();
        message.what = 5;
        mHandler.sendMessage(message);
    }
    void SendDispResult(String str) {
        Message message = new Message();
        message.what = 6;
        message.obj = str;
        mHandler.sendMessage(message);
    }

    @Override
    public void GotData(int data) {
        mListResult.add(data);
        DispCurve();
    }

    @Override
    public void GotData(int[] data) {

    }

    private int getPosition(int pos) {
        return mScanTest.start+pos/mScanTest.step;
    }
    private int getLeft(){
        return getPosition(mScanTest.peakLeft);
    }
    private int getRight(){
        return getPosition(mScanTest.peakRight);
    }
    @Override
    public void Notify(int status) {
        if(status==TestCallback.STATUS_TEST_SUCCESS) {
            mArea1= mScanTest.mArea1;
            mArea2=mScanTest.mArea2;
            String strMsg="测试完成: "+mArea1+"@"+getLeft()+" "+mArea2+"@"+getRight();
            SendDispMessage(strMsg);
            mHandler.sendEmptyMessage(WorkMessage.Finish);
        }else if(status==TestCallback.STATUS_TEST_FAIL)
            SendDispMessage("测试出错");
        else if(status==TestCallback.STATUS_TEST_START)
            SendDispMessage("开始测试");
        else if(status==TestCallback.STATUS_OPEN_LED_FAIL)
            SendDispMessage("开灯失败");
        else if(status==TestCallback.STATUS_MOVE_TRAY_TO_START_FAIL)
            SendDispMessage("移动到起点失败");
        else if(status==TestCallback.STATUS_TEST_FORCE_STOP)
            SendDispMessage("没有接收到停止信号，自动停止");
    }

    private boolean CalcResult() {
        switch (mTestItem) {
            case TEST_ITEM_CORTISOL:
                return CalcResultCortisol();
            case TEST_ITEM_PROGESTERONE:
                return CalcResultProgesterone();
        }
        return false;
    }

    private boolean CalcResultCortisol() {
//        if (mArea1 < 0) return;
//        double y = Math.log10(mArea1);
//        double x = (y - 7.6567) / (-0.755);
//        double result = Math.pow(10, x);
//        if (result < 1)
//            mstrTestResult = "<1";
//        else if (result > 100)
//            mstrTestResult = ">100";
//        else
//            mstrTestResult = ((int) (result * 100)) / 100. + "";
//        int iDot=mstrTestResult.indexOf(".");
//        int nLen=mstrTestResult.length();
//        if(iDot<0)
//            mstrTestResult+=".00";
//        else if(iDot==nLen-2)
//            mstrTestResult+="0";
//        mstrTestResult+="nmol/L";
        if (mArea1 <= 0||mArea2<=0) return false; //新算法不使用Area2的面积
//        double k=-0.6475, b=0.9547;

//        double y=Math.log(1.0*mArea1/mArea2);
//        double x = (y-b)/k;
//        x=Math.exp(x)*3;
//        double result=((int)(x*100+0.5))/100.0;
//        if (result < 1.5)
//            mstrTestResult = "<1.5";
//        else if (result > 375)
//            mstrTestResult = ">375";
//        else
//            mstrTestResult = result + "";
//        double y=Math.log(1.0*mArea1);
        double y=Math.log(mArea1*1.0/mArea2);
        double x = (y-b)/k;
        x=Math.exp(x);
//        x=x*5/3; //2023.08.14 浓度原来稀释3倍，现在是稀释5倍
        double result=((int)(x*100+0.5))/100.0;
        if (result < 0.5)
            mstrTestResult = "<0.5";
        else if (result > 375)
            mstrTestResult = ">375";
        else
            mstrTestResult = result + "";

        int iDot=mstrTestResult.indexOf(".");
        int nLen=mstrTestResult.length();
        if(iDot<0)
            mstrTestResult+=".00";
        else if(iDot==nLen-2)
            mstrTestResult+="0";
        mstrTestResult+="nmol/L";
        return true;
    }

    private boolean CalcResultProgesterone() {
        return false;
    }

    Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    DisplayMessage((String) msg.obj);
                    break;
                case 2:
//                    DisplayData((int[]) msg.obj);
                    break;
                case 3:
                    DrawLineChart();
                    break;
                case 4:
                    DisplayMessage("AD: " + (int) msg.obj);
                    break;
                case 5:
                    findViewById(R.id.btnScanRead).setVisibility(View.VISIBLE);
                    break;
                case 6:
                    DisplayResult((String) msg.obj);
                    break;
                case WorkMessage.Finish:
                    if (!CalcResult())
                        break;
                    if (Constant.isShowArea)
                        SendDispResult("测试结果：" + mstrTestResult + "\t样本号：" + etNumber.getText().toString().trim() + " \tarea1:" + mArea1 + "\tarea2:" + mArea2);
                    else
                        SendDispResult("测试结果：" + mstrTestResult + "\t样本号：" + etNumber.getText().toString().trim());
                    //保存数据
                    saveData();
                    SendShowTestButton();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void DrawLineChart() {
        if (mListResult == null || mListResult.size() <= 0) {
            Toast.makeText(this, "没有数据", Toast.LENGTH_LONG).show();
            return;
        }

        List<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
//        for (int fx = 0; fx < 10; fx++) {
//            if (!bF8ClearNIR[fx]) continue;
        List<Entry> entries = new ArrayList<Entry>();
//            for (int i = 0; i < mListResult.get(fx).size(); i++) {
//                entries.add(new Entry(mStart + i * mStep, mListResult.get(fx).get(i)));
//            }
        for (int i = 0; i < mListResult.size(); i++)
            entries.add(new Entry(mStart + i * 1.0f / mStep, mListResult.get(i)));
//            LineDataSet dataSet = new LineDataSet(entries, mstrWaveLength[fx]);
//        int color = GetColor(fx);
        LineDataSet dataSet = new LineDataSet(entries, "ad");
        int color = GetColor(0);
        dataSet.setColor(color);
        dataSet.setValueTextColor(color);
        dataSet.setCircleColor(color);
        dataSet.setCircleHoleColor(color);
        dataSet.setDrawCircles(false);
        dataSet.setDrawValues(false);
        dataSets.add(dataSet);
//        }
        LineData data = new LineData(dataSets);
        mLineChart.setData(data);
        mLineChart.invalidate(); // refresh
    }

    int[] colors = {Color.RED, Color.GREEN, Color.BLUE, Color.GRAY, Color.DKGRAY, Color.LTGRAY, Color.CYAN, Color.BLACK, Color.MAGENTA, Color.WHITE};

    private int GetColor(int i) {
        return colors[i % 10];
    }

    /**
     * 保存数据
     */
    private void saveData() {
        DataBean dataBean = new DataBean();
        dataBean.time = System.currentTimeMillis();
        //编号
        dataBean.number = etNumber.getText().toString().trim();
        dataBean.create_time = SCTimeUtils.getFormatData03(dataBean.time);

        dataBean.project = mstrTestItem.trim();

        //两个面积
        dataBean.area1 = mArea1 + "";
        dataBean.area2 = mArea2 + "";
        dataBean.result = mstrTestResult;

        dataBean.ad = "0";
        dataBean.start = mStart + "";
        dataBean.stop = mStop + "";
        //步长
        dataBean.step = mStep + "";
        //波长
        dataBean.waveLength = waveLength;
        //亮度
        dataBean.brightness = mBrightness + "";

        if (mbValley) {
            //选择的是胶体金
            dataBean.jtj_or_yg = "1";
        } else {
            dataBean.jtj_or_yg = "2";
        }

        dataBean.save();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_SCAN_RESULT ) {
            if(resultCode == RESULT_OK){
                //扫码返回
                mScanStr = data.getStringExtra("data");
                SCLogUtils.e(TAG, "扫码返回=" + mScanStr);

                if(!GetTestPara()) {
                    Toast.makeText(this, "试纸条参数不正确", Toast.LENGTH_LONG).show();
                }else {
                    SaveAppData.setScanResult(mScanStr);
                    tvScanResult.setText(mScanStr);
                }
            }else {
               Toast.makeText(this,"扫码失败",Toast.LENGTH_SHORT).show();
            }

        }
    }

    private boolean GetTestPara() {
        if(mScanStr.length()<=5) return false;
        if(!mScanStr.substring(0,2).equals("SO")) return false;
        if(!mScanStr.substring(2,3).equals("1")) return false;
        if(!mScanStr.substring(3,4).equals("1")) return false;
        if(!mScanStr.substring(4,5).equals("1")) return false;
        String[] split=mScanStr.substring(5).split(" ");
        if(split==null||split.length!=2) return false;
        k=Double.parseDouble(split[0]);
        b=Double.parseDouble(split[1]);
        return true;
    }
}
